﻿using System;
using Dsl.Ped.Common;
using GalaSoft.MvvmLight.Command;

namespace Dsl.Ped.Editor.Modules.ErrorArea
{
    /// <summary>
    /// View model of the <see cref="ErrorAreaView"/>. This model is used for the handling of an display of errors that 
    /// have occured while the user interacts with the editor. Any time a file crashes to be loaded into an editor or
    /// an exception is thrown from the editor, an editor displays the error in the <see cref="ErrorAreaView"/>
    /// </summary>
    public class ErrorAreaViewModel : ViewModelBase 
    {
        #region Fields

        /// <summary>
        /// Error that occured in the eidotr
        /// </summary>
        private string error;

        /// <summary>
        /// Command executed to reload the loading of a file
        /// </summary>
        private RelayCommand reloadFile;

        /// <summary>
        /// Action executed the reload of the loading of a file
        /// </summary>
        private Action reloadFileAction;

        #endregion

        #region Members

        /// <summary>
        /// Gets or sets the error occured in the editor
        /// </summary>
        public string Error
        {
            get { return error; }
            set 
            { 
                error = value;
                RaisePropertyChanged(() => Error);
            }
        }

        /// <summary>
        /// Gets the command to reload the file
        /// </summary>
        public RelayCommand ReloadFile
        {
            get { return reloadFile ?? (reloadFile = new RelayCommand(this.OnReloadFileCommand)); }
        }

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="ErrorAreaViewModel"/> class.
        /// </summary>
        /// <param name="reloadFileAction">The action for a reload of a file</param>
        public ErrorAreaViewModel(Action reloadFileAction)
        {
            this.reloadFileAction = reloadFileAction;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Set the error to the exception
        /// </summary>
        /// <param name="exc">Exception that has occured in the editor</param>
        public void SetError(Exception exc)
        {
            Error = exc.Message;
        }

        /// <summary>
        /// Hanlder method of the <see cref="ReloadFile"/> command. 
        /// It must reload the loaded file.
        /// </summary>
        private void OnReloadFileCommand()
        {
            reloadFileAction();
        }

        #endregion
    }
}
